#输出分析报告/图片
#
import matplotlib.pyplot as plt
from utils.StandardSqlite3DB import SQLiteDB
from utils.utils import get_files_with_suffix
from PIL import Image
from config import *
import numpy as np

#单个录音文件的鼾声次数保存到sqlite
def report_quqe_to_sqlite(q,recod_path):
    lis_count = []
    while True:
        try:
            m = q.get_nowait()
            lis_count.append(m)
        except:
            print(f"\033[32m 队列为空，等待... \033[0m")
            break  # 队列为空时退出
    print(lis_count)
    for i in lis_count:
        SQLiteDB('data/fenbei_monitor.db').execute(f'INSERT INTO count_{recod_path} (time,count) VALUES (?,?)',(i[0], i[1]))
    print(f"插入数据库完成{len(lis_count)}" )


#单日的报告
def report_day(recod_path):
    res = SQLiteDB('data/fenbei_monitor.db').fetch_all( f'SELECT * FROM count_{recod_path} ORDER BY time ASC')
    _, data_repo_x, data_repo_y = list(map(list, zip(*res)))

    fig = plt.figure(figsize=(30, 2), dpi=300)
    plt.rcParams['font.sans-serif'] = ['SimHei']

    ax1 = fig.add_subplot(111)
    ax1.set_ylim(0, 15)
    ax1.bar(data_repo_x, data_repo_y, color="#4CAF50" ,align='edge')

    #异常值用橙色显示
    mask = np.array(data_repo_y) > F+2
    x_high = np.array(data_repo_x)[mask]
    y_high = np.array(data_repo_y)[mask]
    ax1.bar(x_high, y_high, color="#F39C12", align='edge')

    # 设置新的x刻度位置，步长5
    locs, labels = plt.xticks()
    new_locs = locs[::5]
    ax1.set_xticks(new_locs)

    # 创建新的x轴标签值，保留每个原标签的最后11个字符
    new_labels = [label[-11:-2] for label in data_repo_x[0::5]]
    ax1.set_xticklabels(new_labels)

    # 设置x轴坐标字体大小
    for tick in ax1.get_xticklabels():
        tick.set_fontsize(9)

    # 通过当前坐标轴的patches获取所有柱子
    for bar in plt.gca().patches:
        height = bar.get_height()
        plt.text(bar.get_x() + bar.get_width() / 2., height,
                 f'{height}',
                 ha='center',
                 va='bottom',
                 fontsize=3)

    ax1.set_ylabel('次/分', fontdict={'weight': 'normal', 'size': 10})
    plt.xticks(ha='left',rotation=-45)

    plt.legend(labels=['频次'])
    plt.tight_layout()
    #plt.title('次数图', fontdict={'weight': 'normal', 'size': 20})
    #plt.xlabel('时间')

    plt.axhline(y=F, color='#FF8247', linestyle='--', linewidth=1,label=' ')

    #总打鼾次数
    mask2 = np.array(data_repo_y) < F + 3
    total = np.sum(np.array(data_repo_y)[mask2])

    plt.text(0.001, 0.5, data_repo_x[0][-11:-2].replace("-", "/")+'\n'+data_repo_x[-1][-11:-2].replace("-", "/")+'\n'+str(total)+'次',
             transform=ax1.transAxes,
             fontsize=18,
             va='center',
             ha='left')

    plt.savefig(f'data/report{data_repo_x[0]}.png')

    for tick in ax1.get_xticklabels():
        tick.set_fontsize(3)

    #plt.show()


#所有单日报告汇总到一张图
def report_sum():
    list_report_pho = get_files_with_suffix('data/'  , '.png')
    list_report_pho = [file for file in list_report_pho if file.startswith("report2")]

    images = [Image.open('data/'+img) for img in list_report_pho]
    widths, heights = zip(*(img.size for img in images))
    print(widths, heights)
    max_width = max(widths)
    total_height = sum(heights)
    print(max_width,total_height)
    new_image = Image.new('RGB', (max_width, total_height))

    y_offset = 0
    for img in images:
        new_image.paste(img, (0, y_offset))
        y_offset += img.height

    new_image.save(f'data/report_all.png')
    #pdf
    if pdf_value:
        # 1 inch = 25.4mm → A4 (210mm × 297mm) ≈ 8.27 × 11.69 inches
        dpi = 300
        a4_width_px = int(11.69 * dpi)  # 8.27 inches * 100 DPI = 827 pixels
        a4_height_px = int(8.27 * dpi)  # 11.69 inches * 100 DPI = 1169 pixels

        # 调整图像大小（保持比例，填充 A4）
        new_image.thumbnail((a4_width_px, a4_height_px), Image.LANCZOS)

        # 创建一个 A4 大小的白色背景
        a4_page = Image.new("RGB", (a4_width_px, a4_height_px), "white")

        # 将图像居中粘贴到 A4 页面
        x_offset = (a4_width_px - new_image.width) // 2
        y_offset = (a4_height_px - new_image.height) // 2
        a4_page.paste(new_image, (x_offset, y_offset))

        # 保存为 PDF（指定 DPI）
        a4_page.save("data/report_all.pdf", "PDF", resolution=dpi)

#10万点以上，用浏览器查看流畅
def show_browser():
    pass

if __name__ == '__main__':

    #report_day('recod_20250520_233558')
    report_sum()

